package com.ujoku.view.builder;

import com.ujoku.context.ActionContext;
import com.ujoku.domain.*;
import com.ujoku.service.CartService;
import com.ujoku.service.FavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Created by Greg.Chen on 2015/2/10.
 */
@Component
public class CartBuilder {

    @Autowired
    private ActionContext actionContext;

    @Autowired
    private FavoriteService favoriteService;

    @Autowired
    private CartService cartService;

    public Cart getCart() {
        Cart cart = actionContext.getCart();
        //setFavorite(cart);

        if(cart != null)
            return cart;

        String visitorId = actionContext.getCurrentVisitor().getId();
        cart = cartService.getCart(visitorId);
        if(cart != null)
        {
            cartService.calculateTotal(cart);
            actionContext.setCart(cart);
        }

        return cart;
    }

    private void setFavorite(Cart cart){
        if(cart == null)
            return;

        if(cart.getCartItemList() == null ||  cart.getCartItemList().size() == 0)
            return;

        //设置收藏
        List<Favorite> favoriteList = getFavoriteList();
        cart.getCartItemList().forEach(i->{
            if(favoriteList.stream().anyMatch(g->g.getGoods_id() == i.getGoodsId())){
                i.setIsFav(true);
            }
        });
    }

    private List<Favorite> getFavoriteList(){
        Visitor visitor = actionContext.getCurrentVisitor();
        if(visitor==null){
            return null;
        }

        List<Favorite> favoriteList = favoriteService.getFavoritesByUserId(visitor.getUser_id());
        return favoriteList;
    }

    public Cart reloadCart(){
        actionContext.setCart(null);

        return getCart();
    }

    public void updateRelateInfo(Member member){
        Visitor visitor = actionContext.getCurrentVisitor();
        visitor.setUser_id(member.getUser_id());
        visitor.setDiscount(member.getDiscount());
        visitor.setLevelName(member.getLevelName());
        visitor.setLevel(member.getLevel());


        Cart cart = this.getCart();
        if (cart == null)
            return;

        if (cart.getMemberId() == null || cart.getMemberId() != member.getUser_id() || cart.getLevel() != member.getLevel()) {
            cart.setMemberId(member.getUser_id());
            cart.setLevel(member.getLevel());
            cart.setDiscount(member.getDiscount());
            for (CartItem cartItem : cart.getCartItemList()) {
                cartItem.setPrice(cart.getDiscount() * cartItem.getGoodsPrice());
            }

            cartService.calculateTotal(cart);
            cartService.update(cart);
            actionContext.setCart(cart);
        }
    }
}
